import React, {Component} from 'react'
import {connect} from 'react-redux'
import {actionCreators} from './store'
import Topic from './component/Topic'
import List from './component/List'
import Writer from './component/Writer'
import Recommer from './component/Recommer'
import {
    HomeWrapper,
    HomeLeft,
    HomeRight,
    BackTop
} from './style'


class Home extends Component {
    componentDidMount() {
        this.props.getHomeList()
        this.bindEvents()
    }

    handleScrollTop() {
        window.scrollTo(0, 0)
    }

    componentWillUnmount() {
        window.removeEventListener('scroll',this.props.changeScrollTopShow)
    }

    bindEvents(){
        window.addEventListener('scroll',this.props.changeScrollTopShow)
    }

    render() {
        return (
            <HomeWrapper>
                <HomeLeft>
                    <img className='banner-img'
                         src="//upload.jianshu.io/admin_banners/web_images/4419/31f60ec4cc01cfe02c5bc09bff208d58f2799c3e.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540"
                         alt=""/>
                    <Topic></Topic>
                    <List></List>
                </HomeLeft>
                <HomeRight>
                    <Recommer></Recommer>
                    <Writer></Writer>
                </HomeRight>
                {this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop> : null}
            </HomeWrapper>
        )
    }
}

const mapState = (state) => {
    return {
        showScroll: state.getIn(['home', 'showScroll'])
    }
}

const mapActionToProps = (dispatch) => {
    return {
        getHomeList() {
            const action = actionCreators.getHomeInfo()
            dispatch(action)
        },
        changeScrollTopShow(e){
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            if(scrollTop> 400){
                dispatch(actionCreators.toggleTopShow(true))
            }else{
                dispatch(actionCreators.toggleTopShow(false))
            }
        }
    }
}

export default connect(mapState, mapActionToProps)(Home)